package com.xdqzy.baseline.common.aspect;


import com.xdqzy.baseline.common.exception.BusinessException;
import com.xdqzy.baseline.common.model.RestResult;
import com.xdqzy.baseline.common.utils.WebRequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;

/**
 * @author : winter
 * @version V1.0
 * @Title: rest接口异常处理
 * @ClassName : com.xdqzy.baseline.common.aspect.RestExceptionAdvice.java
 * @Description :
 * @date :  2020-10-27 20:31
 */
@Slf4j
@RestControllerAdvice
public class RestExceptionAdvice {
    @ExceptionHandler(BusinessException.class)
    public RestResult<Void> handlePlatWarnException(BusinessException e) {
        HttpServletRequest request = WebRequestUtils.getRequest();
        log.error("request :{} handle business error", request.getRequestURI(), e);
        return RestResult.buildFail(e.getCode(), e.getErrorMsg());
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public RestResult<Void> handleBindFail(MethodArgumentNotValidException e) {
        HttpServletRequest request = WebRequestUtils.getRequest();
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> errorList = bindingResult.getFieldErrors();
        log.error("request :{} handle param invalid:{}", request.getRequestURI(), errorList, e);
        Optional<FieldError> optional = errorList.stream().findFirst();
        if (optional.isPresent()) {
            FieldError fieldError = optional.get();
            return RestResult.buildFail(1, fieldError.getDefaultMessage());
        }
        return RestResult.buildFail(1, "参数错误");
    }

    @ExceptionHandler({Exception.class})
    public RestResult<Void> handleCommonError(Exception e) {
        HttpServletRequest request = WebRequestUtils.getRequest();
        log.error("request :{} handle unknown error:{}", request.getRequestURI(), e);
        return RestResult.buildFail(1, "内部错误");
    }

}
